/**
 * Created by guoqing on 2019/08/21.
 */
import {
  Token
} from 'token.js';
import {
  Config
} from 'config.js';
class Base {
  constructor() {
    "use strict";
    this.baseRestUrl = Config.restUrl;
    this.onPay = Config.onPay;
  }

  //http 请求类, 当noRefech为true时，不做未授权重试机制
  request(params, noRefetch) {
    if (!params.hideLoading) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
    }
    var that = this,
      url = this.baseRestUrl + params.url;
    if (!params.type) {
      params.type = 'post';
    }
    /*不需要再次组装地址*/
    if (params.setUpUrl == false) {
      url = params.url;
    }
    wx.request({
      url: url,
      data: params.data,
      method: params.type,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        // 判断以2（2xx)开头的状态码为正确
        // 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
        var code = res.statusCode.toString();
        var startChar = code.charAt(0);
        if (startChar == '2') {
          params.sCallback && params.sCallback(res.data);
        } else {
          if (code == '401') {
            if (!noRefetch) {
              that._refetch(params);
            }
          } else if (code === '503') {
            wx.reLaunch({
              url: '/pages/error/index'
            })
          }
          that._processError(res);
          params.eCallback && params.eCallback(res.data);
        }
      },
      fail: function (err) {
        wx.hideLoading();
        //wx.hideNavigationBarLoading();
        that._processError(err);
        params.eCallback && params.eCallback(err);
      },
      complete: function (res) {
        wx.hideLoading({
          fail() {}
        })
      }
    });
  }
  // 二次封装请求promise
  promiseRequest(url, params, needStatus, hideLoading, noRefetch) {
    return new Promise((resolve, reject) => {
      this.request({
        data: params,
        url,
        hideLoading,
        sCallback: data => {
          if (data.status === 200 || data.status === 0) {
            if (needStatus) {
              resolve(data)
            } else {
              resolve(data.data)
            }
          } else if (data.status === 400 && data.errorCode == '10001') {
            const token = new Token()
            wx.login({
              success: ({
                code
              }) => {
                token.getTokenFromServer({
                  appId: Config.appId,
                  refreshToken: true,
                  code
                }, (result) => {
                  if (result.data.login) {
                    this.promiseRequest(url, params, needStatus, noRefetch).then(data => {
                      resolve(data)
                    }).catch(err => {
                      reject(err)
                    })
                  } else {
                    wx.reLaunch({
                      url: '/pages/login/index'
                    })
                  }
                })
              }
            })
          } else if (data.status === 400 && data.errorCode == '10002') {
            wx.reLaunch({
              url: '/pages/login/index'
            })
          } else {
            reject(data)
          }
        },
        eCallback: err => {
          if (err.error || err.message) {
            reject(err)
          } else {
            reject({
              error: '网络错误，请重试'
            })
          }
        }
      }, noRefetch)
    })
  }

  _processError(err) {
    console.log(err);
  }

  _refetch(param) {
    var token = new Token();
    wx.login({
      success: ({
        code
      }) => {
        token.getTokenFromServer({
          appId: Config.appId,
          refreshToken: true,
          code
        }, () => {
          this.request(param, true);
        })
      }
    })
  }

  /*获得元素上的绑定的值*/
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  };

};

export {
  Base
};